﻿using System;
namespace SanLingPLC
{
    public class SanLingPLC
    {
        private ActUtlTypeLib.ActUtlTypeClass _PLCHelper = null;

        public bool Init(ref string result)
        {
            try
            {
                _PLCHelper = new ActUtlTypeLib.ActUtlTypeClass();
                _PLCHelper.ActLogicalStationNumber = int.Parse(this.Port);
                int res=_PLCHelper.Open();
                if (res >= 0)
                {
                    return true;
                }

                return false;
                ////System.Threading.Thread.Sleep(3000);
                //_PLCHelper.Disconnect();
                ////System.Threading.Thread.Sleep(3000);
                //_PLCHelper.Open();
                //return _PLCHelper != null;
            }
            catch (Exception ex)
            {
                result = "PLC Open Error:" + ex.Message+ " 请确认是否安装了三菱PLC驱动  MXComponent  通过TK+6000模块参数配置工具配置IP   在Communication Setup Utility程序中进行相关以太网通讯设置";
                IOHelper.DebugMsg.Log("PLC Open Error:" + ex.Message);
                return false;
            }
        }

        public bool Close(object args)
        {
            _PLCHelper.Disconnect();
            return true;
        }

        public ushort[] ReadRegisterDB(byte regType, string regAddr, int length, byte devID = 0x01)
        {
            try
            {
                short[] buffer = new short[length];
                int ret=this._PLCHelper.ReadDeviceBlock2(regAddr, length, out buffer[0]);
                ushort[] res = new ushort[length];
                string msg = string.Empty;
                msg += "Read Register :";
                for (int i = 0; i < length; i++)
                {
                    res[i] = (ushort)buffer[i];
                    msg += buffer[i].ToString();
                    msg += ";";
                }

                IOHelper.DebugMsg.Log("Read PLC : " + regAddr+"    "+msg);
                return res;
            }
            catch (Exception ex)
            {
                IOHelper.DebugMsg.Log("Read PLC  Error: " + ex.Message);
                return null;
            }
        }


        double ConvertToFloat(short[] buffer, int index, int dotNum = 1)
        {
            if (buffer.Length <= index + 1) return -1f;
            byte[] fbuffer = new byte[4];
            byte[] f1 = BitConverter.GetBytes(buffer[index]);
            byte[] f2 = BitConverter.GetBytes(buffer[index + 1]);

            Array.Copy(f1, fbuffer, 2);
            Array.Copy(f2, 0, fbuffer, 2, 2);
            return Math.Round(BitConverter.ToSingle(fbuffer, 0), dotNum);
        }

        public float[] ReadRegisterF(byte regType, string regAddr, int length, byte devID = 0x01)
        {
            try
            {
                short[] buffer = new short[length * 2];
                this._PLCHelper.ReadDeviceBlock2(regAddr, length * 2, out buffer[0]);
                float[] res = new float[length];
                string msg = string.Empty;
                msg += "Read Register :";
                for (int i = 0; i < length; i += 2)
                {
                    res[i] = (float)ConvertToFloat(buffer, i);
                    msg += res[i].ToString() + ";";
                }
                IOHelper.DebugMsg.Log("Read PLC : " + regAddr + "   " + msg);
                return res;
            }
            catch (Exception ex)
            {
                IOHelper.DebugMsg.Log("Read PLC  Error: " +  ex.Message);
                return null;
            }
        }

        public byte ReadIO(string regAddr, byte devID = 0x01)
        {
            try
            {
                short[] buffer = new short[1];
                this._PLCHelper.ReadDeviceBlock2( regAddr, 1, out buffer[0]);
                string msg = string.Empty;
                msg += "Read Register : " +regAddr +"   ";
                msg += buffer[0].ToString();
                IOHelper.DebugMsg.Log("Read PLC : " + regAddr + "   " + msg);
                return (byte)(buffer[0]);
            }
            catch (Exception ex)
            {
                IOHelper.DebugMsg.Log("Read IO  Error: " + ex.Message);
                return 0x00;
            }
        }

        public bool SetRegisterDB(byte regType, string regAddr, ushort val, byte devID = 0x01)
        {
            //throw new NotImplementedException();
            try
            {
                short[] buffer = new short[1];
                buffer[0] = (short)val;
               int res=  _PLCHelper.WriteDeviceBlock2( regAddr, 1,ref buffer[0]);
                IOHelper.DebugMsg.Log("Set PLC : " + regAddr + "   " + val.ToString());
                return true;
            }
            catch (Exception ex)
            {
                IOHelper.DebugMsg.Log("SetRegister Error:"+ex.Message);
                return false;
            }
        }

        public bool SetRegisters(string regType, string startRegAddr, int length, ushort[] vals, byte devID = 0x01)
        {
            throw new NotImplementedException();
        }
        string _portName = string.Empty;
        public string Port
        {
            get
            {
                return _portName;
            }
            set
            {
                //throw new NotImplementedException();
                _portName = value;
            }
        }
        string _devName = string.Empty;
        /// <summary>
        /// 
        /// </summary>
        public string DevName
        {
            get
            {
                return _devName;
            }
            set
            {
                //throw new NotImplementedException();
                _devName = value;
            }
        }


        public ushort[] ReadRegisterMK(byte regType, string regAddr, int length, byte dbNumber = 0x01)
        {
            throw new NotImplementedException();
        }


        public bool SetRegisterMB(byte regType, string regAddr, byte val, byte devID = 0x01)
        {
            throw new NotImplementedException();
        }


        public float[] ReadRegisterDBF(byte regType, string regAddr, int length, byte dbNumber = 0x01)
        {
            throw new NotImplementedException();
        }
    }
}
